import 'dart:math';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/expert/plan_form/plan_form_detail_entity.dart';
import 'package:ball_lion/entity/expert/plan_form/plan_form_list_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/server/api/expert_api.dart';
import 'package:ball_lion/utils/mode_config.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/widget/history_label.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/widgets/loading/loading_indicator.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';
import 'package:ball_lion/module/mine/user_page_logic.dart';
import 'package:ball_lion/entity/pay/recharge_entity.dart';
import 'package:ball_lion/server/api/coupon_api.dart';
import 'package:ball_lion/server/api/pay_api.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/module/pay/pay_bottom_sheet.dart';

class UserPlanFormList extends StatefulWidget {
  const UserPlanFormList(this.expertId, {super.key, this.tag});

  final String expertId;
  final String? tag;

  @override
  State<UserPlanFormList> createState() => _UserPlanFormListState();
}

class _UserPlanFormListState extends State<UserPlanFormList>
    with AutomaticKeepAliveClientMixin {
  PlanFormList? list;
  late final logic = Get.find<UserPageLogic>(tag: widget.tag);
  final EasyRefreshController refreshController = EasyRefreshController();

  @override
  void initState() {
    getData();
    super.initState();
  }

  Future getData() async {
    list = await ExpertApi.getPlanFormList(widget.expertId);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      color: Colours.greyF2F3F7,
      width: Get.width,
      child: EasyRefresh.builder(
        controller: refreshController,
        onRefresh: getData,
        childBuilder: (BuildContext context, ScrollPhysics physics) =>
            LoadingWidget<bool>(
          isLoading: list == null,
          loading: const LoadingIndicator(),
          data: list?.current == null && list?.history?.length == 0,
          noData: NoDataWidget(needScroll: true, physics: physics),
          child: () => MediaQuery.removePadding(
            removeTop: true,
            context: context,
            child: ListView(
              physics: physics,
              children: [
                if (list?.mark.hasValue == true && ModeConfig.expertRecord)
                  record(),
                LoadingWidget<bool>(
                  isLoading: list?.current == null,
                  loading: Container(),
                  data: list?.current?.issueDetail?.length == 0,
                  noData: Container(),
                  child: () => Block(
                      cardStyle: const CardStyle(
                          margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
                          padding: EdgeInsets.fromLTRB(12, 16, 12, 12)),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          const QsText("最新期次",
                              fontSize: 16,
                              color: Colours.text292D32,
                              fontWeight: FontWeight.w600),
                          issue(list?.current)
                        ].insertEvery(Container(height: 8)),
                      )),
                ),
                LoadingWidget<bool>(
                  isLoading: list?.history == null,
                  loading: Container(),
                  data: list?.history?.length == 0,
                  noData: Container(),
                  child: () => Block(
                      cardStyle: const CardStyle(
                          margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
                          padding: EdgeInsets.fromLTRB(12, 16, 12, 12)),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          const QsText("历史期次",
                              fontSize: 16,
                              color: Colours.text292D32,
                              fontWeight: FontWeight.w600),
                          ...list?.history
                                  ?.map((e) => issue(e))
                                  .toList()
                                  .insertEvery(Container(height: 16)) ??
                              []
                        ].insertEvery(Container(height: 8)),
                      )),
                ),
                Container(height: 100)
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget issue(IssueInfo? entity) {
    bool onSale = entity?.canBuy == true && entity?.purchased == false;
    bool waitStage = entity?.issueState == 1 && entity?.state != 1;
    bool onMatch = entity?.issueState == 1 &&
        entity?.state == 1 &&
        entity?.canBuy == false;
    List<IssueDetail>? list = entity?.issueDetail;
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () => onSale || waitStage
          ? null
          : Get.toNamed(Routes.planFormDetail, arguments: entity?.issueId),
      child: Column(
        children: [
          Row(
            children: [
              QsText("[${entity?.issue ?? 0}期]", color: Colours.blue39407E),
              const Spacer(),
              if (entity?.issueState != 1)
                QsText(entity?.matchTime ?? "",
                    fontSize: 12, color: Colours.grey66)
            ],
          ),
          if (entity?.issueState == 2 || entity?.issueState == 3)
            profitLabel(entity),
          payLabel(entity),
          if (list
                  ?.where((element) =>
                      (onSale || waitStage) ? element.state == 3 : true)
                  .toList()
                  .hasValue ==
              true)
            planForm(IssueForm.fromInfo(list
                    ?.where((element) =>
                        (onSale || waitStage) ? element.state == 3 : true)
                    .toList() ??
                []))
        ].insertEvery(Container(height: 8)),
      ),
    );
  }

  Widget planForm(IssueForm form) {
    List<String> title = ["阶段", "时间", "比赛", "推荐"];
    return Container(
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          border: Border.all(color: Colours.greyE1, width: 0.5)),
      child: DefaultTextStyle(
        style: const TextStyle(fontSize: 12, color: Colours.text),
        child: Column(
          children: [
            Container(
              height: 32,
              color: Colours.greyF2F3F7,
              child: Row(
                  children: [
                SizedBox(
                  width: 32,
                  child: QsText(title[0]).center,
                ),
                Expanded(flex: 2, child: QsText(title[1]).center),
                Expanded(flex: 7, child: QsText(title[2]).center),
                Expanded(flex: 3, child: QsText(title[3]).center)
              ].insertEvery(Container(
                      height: Get.height, width: 0.5, color: Colours.greyE1))),
            ),
            const Divider(height: 0.5, color: Colours.greyE1),
            ...List.generate(form.lines.length, (index) {
              var line = form.lines.reversed.toList()[index];
              return stageLine(line, index);
            }).insertEvery(const Divider(height: 0.5, color: Colours.greyE1))
          ],
        ),
      ),
    );
  }

  Widget record() {
    var record = [list?.tag, list?.profit, list?.maxRed];
    List<String> recordTypeList = ["当前状态", "近n期回报", "最高连红"];
    return Block(
      cardStyle: const CardStyle(
        padding: EdgeInsets.all(16),
        margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          const QsText("计划单战绩", fontSize: 16, fontWeight: FontWeight.w600),
          Container(height: 9),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: List.generate(
                3,
                (childIndex) => Container(
                      width: (Get.width - 40 - 16) / 3 - 1,
                      height: 66,
                      padding: const EdgeInsets.symmetric(vertical: 12),
                      decoration: BoxDecoration(
                        color: Colours.greyF5F7FA,
                        borderRadius: BorderRadius.circular(5.0),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          QsText(record[childIndex] ?? "",
                              fontSize: 16,
                              color: Colours.main,
                              fontWeight: FontWeight.w500),
                          QsText(
                              childIndex == 1
                                  ? list?.profitTitle ?? ""
                                  : recordTypeList[childIndex],
                              fontSize: 12)
                        ],
                      ),
                    )),
          ),
          Container(height: 7),
          if (list?.mark.hasValue == true)
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              physics: const ClampingScrollPhysics(),
              child: Row(
                children: List.generate(
                  list!.mark!.length,
                  (index) => Padding(
                      padding: const EdgeInsets.only(right: 8),
                      child: GestureDetector(
                        onTap: () => Get.toNamed(Routes.planFormDetail,
                            arguments: list?.mark?[index].issueId),
                        child: Transform.rotate(
                          angle: pi / 6,
                          child: HistoryLabel.planForm(
                            width: 28,
                            fontSize: 10,
                            state: list?.mark?[index].state,
                          ),
                        ),
                      )),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget stageLine(StageLine line, int index) {
    return Container(
      color: index % 2 == 0 ? Colours.white : Colours.greyF2F3F7,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
              width: 32,
              height: 44.0 * (line.match?.length ?? 0),
              alignment: Alignment.center,
              child: QsText(line.stage).center),
          Expanded(
            flex: 9,
            child: Column(
                children: List.generate(
                    line.match?.length ?? 0,
                    (index) => contentLine(
                        line.time?[index],
                        line.jcMatchNo?[index],
                        line.match?[index],
                        line.choice?[index])).insertEvery(
                    const Divider(height: 0.5, color: Colours.greyE1))),
          )
        ].insertEvery(Container(
            height: 44.0 * (line.match?.length ?? 0),
            width: 0.5,
            color: Colours.greyE1)),
      ),
    );
  }

  Widget contentLine(
      String? time, String? jcNo, String? match, List<Choice>? choice) {
    return SizedBox(
      height: 44,
      child: Row(
        children: <Widget>[
          Expanded(flex: 2, child: QsText(time ?? "").center),
          Expanded(
              flex: 7,
              child: Row(children: [
                QsText(jcNo ?? "").paddingOnly(left: 5),
                ...List<Widget>.generate(
                    match?.split("vs").length ?? 0,
                    (index) => Expanded(
                          flex: match?.split("vs")[index].length ?? 1,
                          child: QsText(
                            match?.split("vs")[index] ?? "",
                            textAlign:
                                index == 0 ? TextAlign.end : TextAlign.start,
                          ),
                        )).insertEvery(
                    const QsText("vs").paddingSymmetric(horizontal: 2))
              ])),
          Expanded(
              flex: 3,
              child: RichText(
                      text: TextSpan(
                          style: const TextStyle(
                              fontSize: 12, color: Colours.text),
                          children: choice
                              ?.map((e) => TextSpan(
                                  text: e.choice,
                                  style: TextStyle(
                                      color: e.aim == true
                                          ? Colours.main
                                          : Colours.text)))
                              .toList()
                              .insertEvery(const TextSpan(text: "、"))))
                  .center)
        ].insertEvery(
            Container(height: Get.height, width: 0.5, color: Colours.greyE1)),
      ),
    );
  }

  Widget profitLabel(IssueInfo? entity) {
    return SizedBox(
      height: 36,
      child: Stack(alignment: AlignmentDirectional.center, children: [
        Container(
            height: 32,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                color: Colours.greyF2F3F7,
                borderRadius: BorderRadius.circular(4)),
            child: DefaultTextStyle(
              style: const TextStyle(fontSize: 12, color: Colours.text),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  if (entity?.state == 2) ...[
                    const QsText("本期综合回报率 ", needCenter: true),
                    QsText("${((entity?.issueProfit ?? 0) * 100).toInt()}%",
                        needCenter: true, color: Colours.main)
                  ] else ...[
                    const QsText("本期未命中")
                  ]
                ],
              ),
            )),
        Positioned(
            right: 32, child: HistoryLabel.planForm(state: entity?.state))
      ]),
    );
  }

  Widget payLabel(IssueInfo? entity) {
    bool onSale = entity?.canBuy == true && entity?.purchased == false;
    bool waitStage = entity?.issueState == 1 && entity?.state != 1;
    bool onMatch = entity?.issueState == 1 &&
        entity?.state == 1 &&
        entity?.canBuy == false;
    return !waitStage && !onSale && !onMatch
        ? Container()
        : Stack(
            alignment: AlignmentDirectional.center,
            children: [
              Container(
                  height: 60,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Colours.main.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(4),
                      border: Border.all(
                          color: Colours.main.withOpacity(0.5), width: 0.5)),
                  child: Row(
                      mainAxisAlignment: onSale
                          ? MainAxisAlignment.end
                          : MainAxisAlignment.center,
                      children: [
                        QsText(
                            onMatch
                                ? "比赛已开始，暂不可购买"
                                : (waitStage
                                    ? "等待发布"
                                    : "回报率不低于${((entity?.profitMin ?? 0) * 100).toInt()}%"),
                            color: Colours.main,
                            fontWeight: FontWeight.w500),
                        if (onSale) ...[
                          Container(width: 33),
                          GestureDetector(
                              onTap: () => toPay(
                                  entity?.price ?? 0, entity?.issueId ?? 0),
                              child: Container(
                                  height: 30,
                                  margin: const EdgeInsets.only(right: 14),
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 8, vertical: 6),
                                  decoration: BoxDecoration(
                                      color: Colours.main,
                                      borderRadius: BorderRadius.circular(4)),
                                  child: Row(children: [
                                    // Image.asset(Utils.getImgPath("gold_icon_yellow.png"),width: 16),
                                    // Container(width: 2),
                                    QsText(
                                        "${entity?.price?.toStringAsFixed(2) ?? ""}解锁",
                                        needCenter: true,
                                        color: Colours.white,
                                        fontSize: 13,
                                        fontWeight: FontWeight.w400)
                                  ])))
                        ]
                      ])),
              Positioned(
                top: 0,
                left: 0,
                child: Container(
                  height: 17,
                  constraints: const BoxConstraints(minWidth: 55),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          fit: BoxFit.fill,
                          image: AssetImage(
                              Utils.getImgPath("plan_form_tag.png")))),
                  child: QsText(
                      "阶段${((list?.current?.issueStage ?? 0) + (waitStage ? 1 : 0)).toChn}",
                      needCenter: true,
                      fontSize: 10,
                      color: Colours.white),
                ),
              )
            ],
          );
  }

  Future toPay(double price, int issueId) async {
    Utils.onEvent('jhdzf', params: {"jhdzf": 0});
    double money = price.toStringAsFixed(2).toDouble() ?? 0;
    final coupons = await CouponApi.use1Coupons(
        gold: money, scene: PayScene.planForm, otherId: '');
    final PayResult? result = await Get.bottomSheet(
        isScrollControlled: true,
        PayBottomSheet(
            payInfo: PayInfo(
                price: money.toString(),
                payScene: PayScene.planForm,
                buyId: issueId.toString(),
                coupons: coupons)));
    if (result != null && result.toPay == PayStatus.goldPay) {
      var s = await PayApi.planFormOrder(issueId, money,
          couponGold: result.coupon?.gold, couponId: result.coupon?.id);
      if (s == true) {
        Utils.onEvent('pay_done');
        getData();
      } else {
        Utils.onEvent('jhdzf_qxzf');
      }
    } else if (result?.toPay == PayStatus.directPay) {
      Utils.onEvent('jhdzf', params: {"jhdzf": 1});
      getData();
    } else {
      Utils.onEvent('jhdzf_qxzf');
      Toast.text("购买失败");
    }
    User.fetchUserInfo(fetchFocus: false);
  }

  @override
  bool get wantKeepAlive => true;
}
